<?
	global $table_edit, $config_xml_list, $config_xml_edit, $db;
	
	$table_edit = "products";
	
	$sql = "select * from config_view where active = 1 and type = 1 and alias = '".$table_edit."'";
	$arr = $db->getRow($sql);
	$config_xml_list = isset($arr)?$arr['values']:'11111';
	
	$sql = "select * from config_view where active = 1 and type = 2 and alias = '".$table_edit."'";
	$arr = $db->getRow($sql);
	$config_xml_edit = isset($arr)?$arr['values']:'11111';
?>
<?	include("ckeditor_config.php");	
switch($act){
	
	case "list_full":
	ShowListFull();	
	$tpl="list_full";
	break;
	
	case "add_full":
	case "edit_full":	
	EditFull();
	$title_page = "Chỉnh Sửa";
	$tpl="edit_full";
	break;

	
	case "addsm_full":
	case "editsm_full":
	EditSMFull();
	break;
	
	case "del":
	Del();
	break;
		
	case "changeactive":
	ChangeActive("active");
	break;
	
	case "changehome":
	ChangeActive("home");
	break;
	
	case "dellist":
	DelList();
	break;
	
	case "show":
	ChangeShowList("active");
	break;
	
	case "hide":
	ChangeHideList("active");
	break;
		
	case "order":
	Order();
	break;
	
	case "export_full":
	Export();	
	//$tpl="excel_full";
	break;
	
	default:
	ShowListFull();
	$title_page = "CMS - Sản phẩm";
	$tpl="list_full";
		
//	case "edit":	
//	Edit();
//	$title_page = "Chỉnh Sửa";
//	$tpl="edit";
//	break;
//	
//	case "add":	
//	$title_page = "Thêm";
//	$tpl="edit";
//	break;

//	case "addsm":
//	case "editsm":
//	Editsm();
//	break;
	
}

function Export()
{
	global $db;
	error_reporting(E_ALL);
	ini_set('display_errors', TRUE);
	ini_set('display_startup_errors', TRUE);
	date_default_timezone_set('Asia/Saigon');
	
	define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
	
	/** Include PHPExcel */
	//echo 'test'.realpath('./lib/ExcelPHP/PHPExcel.php');
	
	require_once './lib/ExcelPHP/PHPExcel.php';
	
	
	// Create new PHPExcel object
	//echo date('H:i:s') , " Create new PHPExcel object" , EOL;
	$objPHPExcel = new PHPExcel();
	
	$sql = "select * from products ORDER BY `id` ASC";
	$products = $db->getAll($sql);
	// Set document properties
	//echo date('H:i:s') , " Set document properties" , EOL;
	$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
								 ->setLastModifiedBy("Maarten Balliauw")
								 ->setTitle("PHPExcel Test Document")
								 ->setSubject("PHPExcel Test Document")
								 ->setDescription("Test document for PHPExcel, generated using PHP classes.")
								 ->setKeywords("office PHPExcel php")
								 ->setCategory("Test result file");
	$objPHPExcel->getDefaultStyle()->getFont()
                                   ->setName('Times New Roman')
                                   ->setSize(11);
	$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
	$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
	$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
	$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);					   
	$objPHPExcel->getActiveSheet()->getStyle('A2:G2')->getFont()->setBold(true);
	$sql = "select * from products";
	$products = $db->getAll($sql);
	
	if($products)
	{
		$index = 3;
		$stt = 1;
		$objPHPExcel->setActiveSheetIndex(0)
			            ->setCellValue('A2', 'STT')						
						->setCellValue('B2', 'Tên Sản Phẩm')
						->setCellValue('C2', 'Giá Sản Phẩm')
						->setCellValue('D2', 'Mô tả ngắn')
						->setCellValue('E2', 'Hình ảnh')
						->setCellValue('G2', 'ID Sản Phẩm');			
						
		for($i = 0; $i < count($products); $i++)
		{
			$objPHPExcel->setActiveSheetIndex(0)
			            ->setCellValue('A'.$index, $stt)			            
						->setCellValue('B'.$index, $products[$i]['name_vn'])
						->setCellValue('C'.$index, $products[$i]['price'])
						->setCellValue('D'.$index, $products[$i]['short_vn'])
						->setCellValue('E'.$index, 'http://www.thoitrangchonu.com/'.$products[$i]['img'])
						->setCellValue('G'.$index, $products[$i]['id']);
			$stt++;			
			$index++;		
		}
	}
	
	$objPHPExcel->getActiveSheet()->setTitle('Sản Phẩm');
	
	
	// Set active sheet index to the first sheet, so Excel opens this as the first sheet
	$objPHPExcel->setActiveSheetIndex(0);
	
	
	// Save Excel 2007 file
	//echo date('H:i:s') , " Write to Excel2007 format" , EOL;
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
	$today = date("Y-m-d_H-i-s"); 
	$objWriter->save('./files/products-'.$today.'.xlsx');
	//echo date('H:i:s') , " File written to " , 'test1'.'.xlsx';
	// Save Excel5 file
	//echo date('H:i:s') , " Write to Excel5 format" , EOL;
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	$objWriter->save('./files/products.xls');
	//echo date('H:i:s') , " File written to " , 'test1'.'.xls';
	
	
	// Echo memory peak usage
	//echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
	
	// Echo done
	//echo date('H:i:s') , " Done writing files" , EOL;
	//echo 'Files have been created in ' , getcwd() , EOL;
	
		header( "Content-Type: application/vnd.ms-excel" );
		header('Content-Disposition: attachment; filename="http://www.thoitrangchonu.com/files/products.xls"');
		header("Content-Length: " . filesize("http://www.thoitrangchonu.com/files/products.xls"));
		
		readfile("http://www.thoitrangchonu.com/files/products.xls");
			//$fp = fopen("http://www.thoitrangchonu.com/files/products.xls", "r");
			//fpassthru($fp);
			//fclose($fp);
	
}


function EditSMFull()
{
	global $db,$act, $FullUrl, $table_edit, $db_name;	
	
	$sql = "select column_name from information_schema.columns where table_name='".$table_edit."' AND table_schema ='".$db_name."'";
	
	$arr_table = $db->getAll($sql);
	
	$arr = NULL;
	
	for($i = 0; $i < count($arr_table);$i++)
	{
		$name_label = $arr_table[$i]['column_name'];
		//$type_label = $arr_table[$i]['data_type'];
		
		if($name_label == 'cid')
		{
			$arr = ArrPostClean2($arr, 'cid', 'cat');
		}
		else if($name_label == 'active' || $name_label == 'home' || $name_label == 'tn_style')
		{
			$arr = ArrPostCleanActive($arr, $name_label);
		}
		else if($name_label == 'img')
		{
			if(isset($_FILES['img']['name'] ) && $_FILES['img']['size']>0){
				$img = $_FILES['img']['name'];
				$start = strpos($img,".");
				$type = substr($img,$start,strlen($img));
				CheckUpload($type);
				
				$filename = strtolower(substr($img, 0,$start));
				$filename = RenameFile($filename).$type;
				if(file_exists( "./kam/upload/images/products/" . $filename)){
					$filename = substr($img, 0, $start);
					$filename = $_POST["unique_key_vn"] . '-' . time() . $type;
					
				}
				else
				{
					// Khong co
				}
				copy($_FILES['img']['tmp_name'], "./kam/upload/images/products/" . $filename) ;
				$arr['img'] = "kam/upload/images/products/" . $filename;
			}
			else
			{				
				if(isset($_COOKIE['images_drag_flag']))
				{	
					if ($_COOKIE['images_drag_flag'] == 'true' && $_COOKIE['images_drag'] != '' && $_SESSION['images_drag'] != $_COOKIE['images_drag'])
					{
						$arr['img'] = 'kam/upload/images/drag/'.$_COOKIE['images_drag'];
						
						
						//setcookie ("images_drag", "", time()-864000); 
						//setcookie ("images_drag_flag", "", time()-864000); 
						$_SESSION['images_drag'] = $_COOKIE['images_drag'];
						$_SESSION['images_drag_flag'] = false;
						RemoveCookieLive('images_drag');
						RemoveCookieLive('images_drag_flag');
					
					}
				}
				else
				{		
				}
			}
		}
		else
		{
			$arr = ArrPostClean($arr, $name_label);
		}

	}
	
	$arr['content_vn'] = DownloadImage($arr['content_vn']);
	
	//Get Unique Key
	if($arr['name_vn'])
	{
		$unique_key_vn = CreateUniqueKey($arr['name_vn']);		
		$arr['unique_key_vn'] = $unique_key_vn;
		
		$arr['title_vn'] = $arr['keyword_vn'] = $arr['des_vn'] = $arr['seo_f_vn'] = strtolower($arr['name_vn']).", ". CreateTitleKey($arr['name_vn']);
		
		//print($arr['unique_key_vn']);
	}
	//Check Unique Key
	if($test == '1')
	{		
		$nowtime = time();			
		$arr['unique_key_vn'] = $arr['unique_key_vn'] . "-".$nowtime;	
		
	}		
		
	// Kết thúc phần mở rộng
	
	if ($act=="addsm_full")
	{				
		if(!file_exists($arr['img']) || $arr['img'] == '' || !isset($arr['img']))
		{
			if(count($arrImageHost))
			{
				if($arrImageHost[0][0] == '/')
				{
					$str_temp = "";
					for($i = 1; $i < strlen($arrImageHost[0]); $i++)
					{
						$str_temp .= $arrImageHost[0][$i];	
					}	
					$arr['img'] = $str_temp;
				}
				else
					$arr['img'] = $arrImageHost[0];
				
			}
		}
		// Insert User		
		$arr['user_insert'] = $_COOKIE['ad_username'];
		$arr['ip_insert'] = $_SERVER['REMOTE_ADDR'];
		$arr['time_insert'] = date("Y-m-d H:i:s"); 
		
		$postId = vaInsert($table_edit,$arr);
		$msg="Add successfully";	
	}
	else
	{
		// Xử lý Image
		$id=$_POST['id'];
		if (isset($arr['img'])){
			$sqlstmt="select img from ".$table_edit." where id=$id";
			$r = $db->getRow($sqlstmt);
			if(file_exists($r['img'])) unlink($r['img']);
		}
		
		// Insert Log		
		$arr['user_update'] = $_COOKIE['ad_username'];
		$arr['ip_update'] = $_SERVER['REMOTE_ADDR'];
		$arr['time_update'] = date("Y-m-d H:i:s"); 
		
		vaUpdate($table_edit, $arr,' id='.$id);	
		$msg="Đã Edit successfully";	
	}
	
	$msg="Add successfully";
	$_SESSION['mess'] = $msg;
	$page="admin-pro.html?do=".$table_edit. (isset($_GET['page'])?'&page='.$_GET['page']:'');

	//print_r($arr);
	page_transfer2($page);		
}

?>
